﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using System.Reflection;
using System.Xml;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.MobileControls;

namespace VNTG.CustomFieldTypes
{
    public class AdvancedComputedField : SPFieldComputed
    {
        #region Constructors
         public AdvancedComputedField(SPFieldCollection fields, string fieldName)
           : base(fields, fieldName)
        { }

         public AdvancedComputedField(SPFieldCollection fields, string typeName, string displayName)
            : base(fields, typeName, displayName)
        { }
        #endregion

        #region Implementation of Get/Set InnerXmlForNode
        public void SetInnerXmlForNode(string nodeName, string innerXml)
        {
            Type fldType = this.GetType();

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(String.Format("<{0}>{1}</{0}>", nodeName, innerXml));

            MethodInfo miSetXml = fldType.GetMethod("SetInnerXmlForNode", BindingFlags.Instance | BindingFlags.NonPublic);
            miSetXml.Invoke(this, new object[] { nodeName, doc.DocumentElement.InnerXml });
        }

        public string GetInnerXmlForNode(string nodeName)
        {
            string result = null;

            Type fldType = this.GetType();

            MethodInfo miGetXml = fldType.GetMethod("GetNodeFromXmlDom", BindingFlags.Instance | BindingFlags.NonPublic);
            XmlNode resultNode = miGetXml.Invoke(this, new object[] { nodeName }) as XmlNode;

            if (resultNode != null)
            {
                StringBuilder sb = new StringBuilder();
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent = true;
                settings.ConformanceLevel = ConformanceLevel.Fragment;
                using (XmlWriter writer = XmlTextWriter.Create(sb, settings))
                {
                    resultNode.WriteContentTo(writer);
                }

                result = sb.ToString();
            }

            return result;
        }
        #endregion
    }
}
